# coding: utf-8
# @Author: 莫小鱼
import time
from datetime import timedelta
import pytest

from AutoApiTest.configs.setting import is_dd_msg
from AutoApiTest.unit_tools.emialReport import send_dd_msg
from AutoApiTest.unit_tools.handle_data.yaml_handler import clear_yaml


@pytest.fixture(scope="session", autouse=True)
def cleat_extract():
    clear_yaml()


def format_duration(seconds):
    """将秒数转换成时分秒格式"""
    return str(timedelta(seconds=seconds)).split('.')[0]


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    Pytest框架预定义的钩子函数，用于测试结束后自动化收集测试结果
    :param terminalreporter:
    :param exitstatus:
    :param config:
    :return:
    """
    testcase_total = terminalreporter._numcollected
    passed_num = len(terminalreporter.stats.get('passed', []))
    failed_num = len(terminalreporter.stats.get('failed', []))
    error_num = len(terminalreporter.stats.get('error', []))
    skipped_num = len(terminalreporter.stats.get('skipped', []))
    duration = round(time.time() - terminalreporter._sessionstarttime, 2)
    formatted_duration = format_duration(duration)

    # 统计通过率，失败率，错误率
    pass_rate = f"{(passed_num/testcase_total)*100:.0f}%" if testcase_total > 0 else "N/A"
    failed_rate = f"{(failed_num/testcase_total)*100:.0f}%" if testcase_total > 0 else "N/A"
    error_rate = f"{(error_num / testcase_total) * 100:.0f}%" if testcase_total > 0 else "N/A"

    summary = f"""
    接口自动化测试结果通知：
    *...*...*...*...*...*...*...*...*...*...*...*...*...*
    测试用例总数：{testcase_total}
    测试用例通过数：{passed_num}
    通过率：{pass_rate}
    测试用例失败数：{failed_num}  
    失败率：{failed_rate}
    测试用例错误数：{error_num}   
    错误率：{error_rate}
    测试用例跳过数：{skipped_num}
    测试执行总时长：{duration}s ({formatted_duration})
    *...*...*...*...*...*...*...*...*...*...*...*...*...*
    """
    if is_dd_msg:
        send_dd_msg(summary)
